package com.ruoyi.am.utils;

import com.ruoyi.am.controller.AmRosterController;
import com.ruoyi.am.domain.AmCarPlace;
import com.ruoyi.am.domain.AmDriver;
import com.ruoyi.am.domain.AmRoute;
import com.ruoyi.am.service.IAmCarPlaceService;
import com.ruoyi.am.service.IAmDriverService;
import com.ruoyi.am.service.IAmRouteService;
import com.ruoyi.common.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;

import javax.annotation.Resource;
import java.io.*;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.List;

@Component
public class SocketThread extends Thread{

    private Socket socket = null;

    private AmDriver amDriver = null;

    private int driver_id = -1;
    @Autowired
    private AmRosterController AmRoster;
    @Resource
    private IAmDriverService amDriverService;

    public SocketThread(){}

    public SocketThread(Socket socket){
        this.socket = socket;
    }

    @Override
    public void run() {

        try {
            // 由Socket对象得到输入流，并构造相应的BufferedReader对象
            InputStream inputStream = socket.getInputStream();
            byte[] bytes = new byte[1024];
            StringBuilder sb = new StringBuilder();
            int len = inputStream.read(bytes);
            sb.append(new String(bytes, 0, len,"GB2312"));

            // 由Socket对象得到输出流，并构造PrintWriter对象
//            PrintWriter os = new PrintWriter(socket.getOutputStream(), true);

            String message = sb.toString();
            System.out.println(message);
            String result = analysis(message);
            OutputStream outputStream = socket.getOutputStream();
            outputStream.write(result.getBytes("GB2312"));
            outputStream.flush();
            outputStream.close();
            System.out.println("response: "+result);

            // 关闭Socket
            socket.close();

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public String getRoster(int id){
        String roster = BeanUtil.getAmRoster().getOneOrder(amDriver.getName(), new Date().getDay());
        String result = amDriver.getName();
        if (roster.equals("399")) {
            result += ",无班,79%";
        }
        else
            result += ","+roster+",79%";
        return result;
    }

    public AmDriver getDriverById(int driver_id){
        return BeanUtil.getiAmDriverService().selectAmDriverById((long)driver_id);
    }

    public String analysis(String message){
        if(!message.startsWith("$"))
            return "message form error";
        try {
            String id = message.substring(1,5);
            int device_id = CommonUtil.parseHex4(id);
            driver_id = getDriverByDevice(device_id);
            amDriver = getDriverById(driver_id);
            String order = message.substring(5, 6);
            String data = message.substring(6,message.length()-3);
            return toMethod(order, data, id);
        }
        catch (Exception e){
            e.printStackTrace();
            return "error02";
        }

    }

    public int getDriverByDevice(int device){
        if(device == 1)
            driver_id = 101;
        return driver_id;
    }

    public String toMethod(String order, String data, String id){

        switch (order){
            case "1": return getRoster(driver_id);
            case "A": return updateStatus("0");
            case "B": return updateStatus("1");
            case "C": return updateStatus("2");
            case "P": return updatePlace(data, id);
        }

        return "no such method";
    }

    private String updatePlace(String data, String id) {
        IAmCarPlaceService amCarPlaceService = BeanUtil.getiAmCarPlaceService();
        AmCarPlace place = new AmCarPlace();
        place.setCarNum(amDriver.getCarId());
        List<AmCarPlace> list = amCarPlaceService.selectAmCarPlaceList(place);

        if (list.size()==0){
            AmCarPlace amCarPlace = new AmCarPlace();
            amCarPlace.setPlace(data);
            amCarPlace.setDriverId((long) driver_id);
            amCarPlace.setDriverName(amDriver.getName());
            amCarPlace.setUpdateTime(DateUtils.getNowDate());
            amCarPlace.setCarNum(amDriver.getDriverNum());
            amCarPlace.setStatus("-1");
            amCarPlaceService.insertAmCarPlace(amCarPlace);
        }
        else if (list.size()==1){
            AmCarPlace amCarPlace = list.get(0);
            amCarPlace.setPlace(data);
            amCarPlace.setUpdateTime(DateUtils.getNowDate());
            amCarPlaceService.updateAmCarPlace(amCarPlace);
        }
        else {
            System.out.println("UpdatePlace Error!");
        }

        return getRoute(id);
    }

    public String updateStatus(String sta){

        IAmCarPlaceService amCarPlaceService = BeanUtil.getiAmCarPlaceService();
        IAmRouteService iAmRouteService = BeanUtil.getiAmRouteService();

        AmRoute amRoute = new AmRoute();
        amRoute.setDriverId((long) driver_id);
        List<AmRoute> list = iAmRouteService.selectAmRouteList(amRoute);
        for(AmRoute route:list){
            int status = Integer.parseInt(route.getStatus());
            if(status >= -1 && status < 2){
                route.setStatus(sta);
                if(sta.equals("1")){
                    route.setRecieveTime(DateUtils.getNowDate());
                }
                else if(sta.equals("2")){
                    route.setFinTime(DateUtils.getNowDate());
                }
                iAmRouteService.updateAmRoute(route);
                break;
            }
        }

        AmCarPlace place = new AmCarPlace();
        place.setDriverId((long)driver_id);
        List<AmCarPlace> list1 = amCarPlaceService.selectAmCarPlaceList(place);
        if(list1.size()==1){
            AmCarPlace carPlace = list1.get(0);
            carPlace.setStatus(sta);
            if(sta.equals("2"))
                carPlace.setStatus("-1");
            amCarPlaceService.updateAmCarPlace(carPlace);
        }
        else {
            System.out.println("UpdatePlace Error!");
        }

        return "ok";
    }

    public String getRoute(String id){
        IAmRouteService iAmRouteService = BeanUtil.getiAmRouteService();
        AmRoute route = new AmRoute();
        route.setStatus("-1");
        route.setDriverId((long) driver_id);
        List<AmRoute> list = iAmRouteService.selectAmRouteList(route);
        if (list.size()==1){
            AmRoute amRoute = list.get(0);
            return "$" + id + "2" + amRoute.getPatPlace() + "," + amRoute.getPatPhone() + ","
                    + amRoute.getDoctor() +"," +amRoute.getNourse() +"#kk";
        }
        else if(list.size() == 0)
            return "no task";
        else {
            System.out.println("GetRoute Error!");
            return "error03";
        }
    }

}
